<?php

namespace App\Jobs\Stats\PlayerBet;

use App\Jobs\Stats\Stats as JobStats;
use App\Models\Admin\Stats\PlayerBet\Day as Stats;
use App\Models\Game\Settlement\Info;

class Day extends JobStats
{

    /**
     * 执行统计任务。
     *
     * @return void
     */
    public function stats()
    {
        $columns[] = 'uid,currency,account_id,line_code';
        $columns[] = 'COUNT(*) as doc_count';
        $columns[] = 'SUM(bet_base) as bet_base';
        $columns[] = 'SUM(bet_num) as bet_num';
        $columns[] = 'SUM(gain_player) as gain_player';
        $columns[] = "CAST(SUM(usd->'$.bet_base') AS DECIMAL({$this->decimals()},{$this->precision()})) AS usd_bet_base";
        $columns[] = "CAST(SUM(usd->'$.bet_num') AS DECIMAL({$this->decimals()},{$this->precision()})) AS usd_bet_num";
        $columns[] = "CAST(SUM(usd->'$.gain_player') AS DECIMAL({$this->decimals()},{$this->precision()})) AS usd_gain_player";

        $stats = Info::dbTable()->selectRaw(implode(',', $columns))
            ->where('status', Info::STATUS_NORMAL)
            ->where('player_type', Info::PLAYER_TYPE)
            ->where('end_time', '<', $this->task->timed + 86400)
            ->where('end_time', '>=', $this->task->timed)
            ->where('plat_code', $this->task->plat_code)
            ->where('game_id', $this->task->game_id)
            ->where('scene_id', $this->task->scene_id)
            ->groupBy('uid', 'currency')
            ->get();

        $stats->each(function ($item) {
            Stats::updateOrCreate(
                $this->task->only(['timed', 'plat_code', 'game_id', 'scene_id']) +
                ['uid' => $item['uid'], 'currency' => $item['currency']],
                [
                    'account_id' => $item['account_id'], 'line_code' => $item['line_code'],
                    'doc_count' => $item['doc_count'], 'bet_base' => $item['bet_base'],
                    'bet_num' => $item['bet_num'], 'gain_player' => $item['gain_player'],
                    'amount' => -$item['gain_player'],
                    'usd' => [
                        'bet_base' => $this->makeRound($item['usd_bet_base']),
                        'bet_num' => $this->makeRound($item['usd_bet_num']),
                        'gain_player' => $this->makeRound($item['usd_gain_player']),
                        'amount' => $this->makeRound(-$item['usd_gain_player']),
                    ]
                ]
            );
        });
    }
}
